<template>
  <div>
    <el-form :model="user" label-width="100px">
      <el-form-item label="Username">
        <el-input v-model="username" type="text" clearable></el-input>
      </el-form-item>
      <el-form-item label="Password">
        <el-input v-model="password" type="password" show-password></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="insertUser">添加</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import {ref} from 'vue';
import axios from 'axios';
import {urlData} from "@/utils/url.js";
import {useRouter} from "vue-router";

const router = useRouter();
import qs from 'qs';
import {ElMessage} from "element-plus";

const user = ref(null);
const username = ref('');
const password = ref('');
//username是否为字母的正则表达式
const usernameReg = /^[a-zA-Z0-9]+$/;
//password是否为字母和数字的正则表达式
const passwordReg = /^[a-zA-Z0-9]+$/;

const validateInput = () => {
  if (username.value === '') {
    ElMessage.error('用户名不能为空');
    return false;
  } else if (!usernameReg.test(username.value)) {
    ElMessage.error('用户名只能包含字母和数字');
    return false;
  } else if (password.value === '') {
    ElMessage.error('密码不能为空');
    return false;
  } else if (!passwordReg.test(password.value)) {
    ElMessage.error('密码只能包含字母和数字');
    return false;
  }
  return true;
};

const insertUser = async () => {
  console.log('Update user:', username.value, password.value);
  if (!validateInput()) {
    return;
  }
  // 发送请求
  try {
    await axios.post(`${urlData('addUser')}`, qs.stringify({
          username: username.value,
          password: password.value
        })
    );
    ElMessage.success('添加成功');
    router.push({name: 'detail'});
  } catch (error) {
    ElMessage.error('添加失败');
    console.error('Update failed:', error);
  }
};
</script>
<style scoped>

</style>